import datetime

from rest_framework.serializers import (ModelSerializer, ReadOnlyField,
                                        SerializerMethodField)

from company.models import Company, Driver, Vehicle, VehicleCompanyTerminal
from location.models import VehicleStatus
from terminal.models import Terminal
from terminal.serializers import TerminalSerializer, TerminalCreateSerializer


class CompanySerializer(ModelSerializer):
    class Meta:
        model = Company
        fields = '__all__'


class DriverSerializer(ModelSerializer):
    class Meta:
        model = Driver
        fields = '__all__'

    def to_representation(self, instance):
        return {
            'id': instance.id,
            'name': instance.name,
            'gender': instance.get_gender_display(),
            'phone_number': instance.phone_number,
            'portrait_url': instance.portrait_url,
            'created_time': instance.created_time.strftime('%Y-%m-%d %H:%M:%S')
        }


class VehicleSerializer(ModelSerializer):
    class Meta:
        model = Vehicle
        fields = (
            'id', 'license_number', 'vin',
        )


class VehicleCreateSerializer(ModelSerializer):
    class Meta:
        model = Vehicle
        fields = '__all__'


class VehicleTerminalSerializer(ModelSerializer):
    license_number = ReadOnlyField(source='vehicle.license_number')
    imei = ReadOnlyField(source='terminal.imei')

    class Meta:
        model = VehicleCompanyTerminal
        fields = ('license_number', 'imei', 'created_time')


class VehicleCompanyTerminalSerializer(ModelSerializer):
    vehicle = VehicleCreateSerializer()
    company = CompanySerializer()
    terminal = TerminalCreateSerializer()

    class Meta:
        model = VehicleCompanyTerminal
        fields = ('vehicle', 'company', 'terminal')

    def create(self, validated_data):
        vehicle_info, _ = Vehicle.objects.get_or_create(**validated_data.pop('vehicle'))
        company_info, _ = Company.objects.get_or_create(**validated_data.pop('company'))
        terminal_info, _ = Terminal.objects.get_or_create(**validated_data.pop('terminal'))
        if not VehicleStatus.objects.filter(vehicle=vehicle_info).first():
            VehicleStatus.objects.get_or_create(status="OFFLINE", vehicle=vehicle_info,
                                                last_time=datetime.datetime.now())

        vct, _ = VehicleCompanyTerminal.objects.get_or_create(
            vehicle=vehicle_info,
            company=company_info,
            terminal=terminal_info)
        return vct
